<template>
    <div class="update">
        <h1>动态更新</h1>
        <div ref="echartRef" class="echart"></div>
        <h3>集齐七天不洗头你的愿望是什么？</h3>
        <button @click="updateEchart(0)" class="blue">脱单</button>
        <button @click="updateEchart(1)" class="green">双休</button>
        <button @click="updateEchart(2)" class="orange">暴富</button>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
type SeriesData = {
    value: number;
    name: string;
}[];
interface Series extends echarts.EChartsCoreOption {
    series: {
        data: SeriesData;
    }[];
}
let pieChart: echarts.ECharts
onMounted(() => {
    // 初始化报表
    if (echartRef.value) {
        pieChart = echarts.init(echartRef.value)
        option_pie.series[0].data = requestData
        pieChart.setOption(option_pie)
    }
})
const echartRef = ref<HTMLElement>()
const option_pie = {
    title: {
        text: '饼图',
        subtext: '',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
        {
            name: '',
            type: 'pie',
            radius: '50%',
            data: [] as SeriesData,
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
}
// 模拟服务器获取的数据
let requestData = [
    { value: 1, name: '脱单' },
    { value: 1, name: '双休' },
    { value: 1, name: '暴富' },
]
// 点击更新报表
const updateEchart = (id: number | undefined) => {
    // 模拟数据更新
    if (id != undefined) requestData[id].value += 1
    if (pieChart) {
        // 获取报表option实例
        let option = pieChart.getOption() as Series
        // 给实例赋上新的值
        option.series[0].data = requestData
        // 二次更新图表
        pieChart.setOption(option)
    }
}
</script>
<style lang="scss" scoped>
.update {
    margin: auto;
    max-width: 60vw;

    .echart {
        width: 100%;
        height: 450px;
    }

    button {
        margin: 0 10px;
        color: white;
        cursor: cell;
    }

    .blue {
        background: #5470C6;
    }

    .green {
        background: #95D178;
    }

    .orange {
        background: #FAC858;
    }
}
</style>